#include "type.h"

int writeScreen(int fd)
{
	int bytesRead = 0, newLines = 0;
	char buf = '\0';
	
	do
	{
		bytesRead = do_read(fd, &buf, 1);
		do_write(1, &buf, bytesRead);
		if (buf == '\n')
		{
			buf = '\r';
			do_write(1, &buf, 1);
			++newLines;
		}
	} while (bytesRead == 1 && newLines < 25);
	
	if (newLines < 25) return 0;
	else return 1;
}

int writeChar(int fd)
{
	int bytesRead = 0;
	char buf = '\0';
	
	bytesRead = do_read(fd, &buf, 1);
	do_write(1, &buf, bytesRead);
	
	if (bytesRead == 1) return 1;
	else return 0;
}

void main(int argc, char* argv[])
{
	int fd = -1, screenFd = -1, keepGoing = 1;
	char choice = '\0', *file;
	
	do_write(2, "*****************************\n\r", 31);
	do_write(2, "*      JRR More Program     *\n\r", 31);
	do_write(2, "*****************************\n\r", 31);
	
	if (argc == 1)
	{
		if (contains(' ', argv[0]))
		{
			strtok(argv[0], " ");
			file = argv[0] + strlen(argv[0]) + 1;
			fd = open(file, READ);
			screenFd = 0;
			do_write(2, "Reading from \"", 14);
			do_write(2, file, strlen(file));
			do_write(2, "\"\n\r", 3);
		}
		else // Read from stdin
		{
			char tty[50];
			fd = 0;
			do_gettty(tty);
			screenFd = open(tty, READ);
			do_write(2, "Reading from stdin\n\r", 20);
		}
	}
	else if (argc == 2)
	{
		file = argv[1];
		fd = open(argv[1], READ);
		screenFd = 0;
		do_write(2, "Reading from \"", 14);
		do_write(2, argv[1], strlen(argv[1]));
		do_write(2, "\"\n\r", 3);
	}
	else
	{
		printf("Usage: more filename\n");
		return;
	}
	
	if (fd > -1)
	{
		keepGoing = writeScreen(fd);
		while (keepGoing)
		{
			do_read(screenFd, &choice, 1);
			switch(choice)
			{
				case ' ':
				{
					keepGoing = writeChar(fd);
				} break;
				
				case '\r':
				case '\n':
				{
					keepGoing = writeScreen(fd);
				} break;
			}
		}
		
		do_close(fd);
	}
	else
	{
		printf("Unable to open \"%s\"!\n", argv[1]);
	}
}
